package com.example.app3

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.app.Activity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.ActivityResult

class MainActivity : AppCompatActivity() {
    private var tvResult: TextView? = null

    // 注册Activity结果监听器（显式处理类型）
    private val activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data: Intent? = result.data
            data?.let { intent ->
                val resultStr = intent.getStringExtra("result")
                tvResult?.text = String.format(getString(R.string.returned_result), resultStr)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvResult = findViewById(R.id.tv_result)

        // 启动SecondActivity1
        val btnActivity1 = findViewById<Button>(R.id.btn_activity1)
        btnActivity1.setOnClickListener {
            val intent = Intent(this, SecondActivity1::class.java)
            intent.putExtra("message", getString(R.string.param_message))
            startActivity(intent)
        }

        // 启动SecondActivity2（带结果返回）
        val btnActivity2 = findViewById<Button>(R.id.btn_activity2)
        btnActivity2.setOnClickListener {
            val intent = Intent(this, SecondActivity2::class.java)
            activityResultLauncher.launch(intent)
        }

        // 启动SecondActivity3（相机）
        val btnActivity3 = findViewById<Button>(R.id.btn_activity3)
        btnActivity3.setOnClickListener {
            val intent = Intent(this, SecondActivity3::class.java)
            startActivity(intent)
        }

        // 启动SecondActivity4（秒表）
        val btnActivity4 = findViewById<Button>(R.id.btn_activity4)
        btnActivity4.setOnClickListener {
            val intent = Intent(this, SecondActivity4::class.java)
            startActivity(intent)
        }
    }
}